<template>
    <view class="content">
        <!-- 渐变色 -->
        <view class="positioning"></view>
        <!-- 购物车列表 -->
        <checkbox-group>
            <view class="car-box" v-for="item in shops" :key="item.id">
                <view class="box-top" @click.stop="shopDetas1(item)">
                    <checkbox @click.stop="shopGoods(item)" :checked="item.ischall" class="red round" value="cb" style="transform: scale(0.7)" />
                    <image class="img" src="@/static/carimg.png" mode=""></image>
                    <view class="">{{ item.name }}</view>
                </view>
                <view class="box-bottom" v-for="it in item.goodsList" :key="it.id">
                    <checkbox @click="goods(it, item)" :checked="it.ischak" class="red round" value="cb" style="transform: scale(0.7)" />
                    <image @click.stop="shopDetas2(it)" class="img" :src="it.goods.image" mode="aspectFit"></image>
                    <view>
                        <view class="nickname">{{ it.goods.title }}</view>
                        <view class="nickname" style="color: #9e9e9e">{{ it.sku_price.goods_sku_text }}</view>
                        <view class="box-btm">
                            <view class="btm-left">￥{{ it.goods.price }}</view>
                            <view class="btm-right">
                                <wd-input-number v-model="it.goods_num" @change.stop="handleChange(it)" disable-input />
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 底部-->
            <view class="fotter" v-if="shops.length >= 1">
                <view @click="allxuan" class="fot-left">
                    <checkbox :checked="allx" class="red round" value="cb" style="transform: scale(0.7)" />
                    全选
                </view>
                <view class="fot-right">
                    合计
                    <text style="color: #ff9c01">￥{{ Math.max(totalPrice, 0).toFixed(2) }}</text>
                    <view class="gouwuce">
                        <view @click="btnClick" class="btnsty jie">结算</view>
                        <view @click="delCarClick" class="btnsty">删除</view>
                    </view>
                </view>
            </view>
        </checkbox-group>
    </view>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { carList, carUPdate, user, getCreate, delCar } from '@/api/index.js';
import { onShow } from '@dcloudio/uni-app';
import { utils } from '../../utils/utils';
const value = ref(0);
const totalPrice = ref(0); //商品总价格
const allx = ref(false); //底部全选
const list11 = ref({}); //购物车列表
const idss = ref([]); //购物车id
const parmsCar = ref({
    voucher: 0,
    list: []
}); //创建订单参数
onMounted(() => {});
onShow(async () => {
    totalPrice.value = 0;
    allx.value = false;
    // 获取购物车列表
    await getCarList();
    // 增加购物车列表状态
    countPrice();
    userInfo(); //个人信息
});
// 点击删除
const delCarClick = async () => {
    if (idss.value.length <= 0) return utils('请选中商品进行删除!');
    const ret = await delCar(idss.value.join(','));
    if (ret.code == 1) {
        totalPrice.value = 0;
        allx.value = false;
        // 获取购物车列表
        await getCarList();
        // 增加购物车列表状态
        countPrice();
        utils(ret.msg);
    } else {
        utils(ret.msg);
    }
};
// 点击结算
const btnClick = async () => {
    if (idss.value.length <= 0) return utils('商品不能为空!');
    console.log('点击结算');
    const ret = await getCreate(parmsCar.value);
    if (ret.code == 1) {
        uni.navigateTo({
            url: `/pages/sub/myOrder?activeIndex=2`
        });
        utils(ret.msg);
        delCar(idss.value.join(',')); //删除购物车
    } else {
        utils(ret.msg);
    }
};

// 商铺选中 item1商铺信息
const shopGoods = (item1) => {
    console.log(777, item1);
    // 创建订单数据

    const find = parmsCar.value.list.findIndex((item) => item.shop_id == item1.id);
    // 如果之前选中过商品
    if (find != -1) {
        parmsCar.value.list[find].goods_list = [];
        console.log('有商铺', parmsCar.value.list);
    } else {
        parmsCar.value.list.push({ shop_id: item1.id, goods_list: [] });
    }

    item1.ischall = !item1.ischall;
    // 当选中店铺的时候遍历商品，把商品状态改为true
    if (item1.ischall == true) {
        const finds = parmsCar.value.list.findIndex((item) => item.shop_id == item1.id);
        item1.goodsList.forEach((it) => {
            parmsCar.value.list[finds].goods_list.push({ goods_id: it.goods_id, goods_sku_price_id: it.goods_sku_price_id, goods_num: it.goods_num });
            // 如果没有选中就把没选中的商品状态改成选中
            if (it.ischak != true) {
                it.ischak = true;
                idss.value.push(it.id);
                console.log(idss.value);
                const priceToAdd = Number(it.goods_num) * Number(it.snapshot_price); //遍历当前店铺所有商品计算他的价格
                totalPrice.value = Number(priceToAdd) + Number(totalPrice.value); //累加当前店铺所有商品的价格
            }
        });

        // 如果所有店铺都选中，就把全选按钮选中
        allx.value = shops.value.every((it) => it.ischall == true);
    } else {
        parmsCar.value.list.splice(parmsCar.value.list[find], 1);
        // 取消商铺选中
        item1.goodsList.forEach((it) => {
            it.ischak = false; //把所有商品状态改成false
            idss.value = idss.value.filter((item) => item !== it.id);
            console.log('取消店铺选中', idss.value);
            const priceToRemove = it.goods_num * it.snapshot_price; //取消当前商品的价格
            totalPrice.value = totalPrice.value - priceToRemove; //减去当前店铺所有商品的价格
        });
        allx.value = false; //取消全选按钮
    }
    console.log(999, parmsCar.value.list);
};
//商品选中  item1当前商品信息，item2当前商铺信息
const goods = (item1, item2) => {
    console.log(item1);
    console.log(item2);
    item1.ischak = !item1.ischak;
    // 判断当前店铺是否所有商品数据都选中
    const goodp = item2.goodsList.every((item) => {
        return item.ischak == true;
    });
    // 如果当前店铺所有商品都选中
    if (goodp) {
        item2.ischall = true; //选中店铺
        //判断列表所有的店铺按钮是否选中，改变全选的状态
        allx.value = shops.value.every((it) => {
            return it.ischall == true;
        });
    } else {
        item2.ischall = false; //取消店铺选中
        allx.value = false; //取消全选
    }
    // 计算价格
    if (item1.ischak == true) {
        idss.value.push(item1.id); //把购物车id推到数组里
        // 计算并累加价格
        const priceToAdd = item1.goods_num * item1.snapshot_price; //每个商品选中的价格
        totalPrice.value += priceToAdd; //选中多个商品把价格累加到一起

        // 创建订单数据
        const find = parmsCar.value.list.findIndex((item) => item.shop_id == item1.shop_id);
        if (find !== -1) {
            // 如果找到了，添加到 goods_list
            parmsCar.value.list[find].goods_list.push({ goods_id: item1.goods_id, goods_sku_price_id: item1.goods_sku_price_id, goods_num: item1.goods_num });
            console.log('找到了', parmsCar.value);
        } else {
            // 如果没有找到，添加一个新的 shop 对象
            parmsCar.value.list.push({
                shop_id: item1.shop_id,
                goods_list: [{ goods_id: item1.goods_id, goods_sku_price_id: item1.goods_sku_price_id, goods_num: item1.goods_num }]
            });
            console.log('没找到', parmsCar.value);
        }
    } else {
        const findcar = idss.value.findIndex((item) => item == item1.id);
        if (findcar != -1) {
            idss.value.splice(findcar, 1);
        }
        // 从总价格中减去商品的价格
        const priceToRemove = item1.goods_num * item1.snapshot_price; //取消当前商品的价格
        totalPrice.value -= priceToRemove; //减去当前商品的价格

        // 创建订单数据,找到当前店铺索引
        const find = parmsCar.value.list.findIndex((item) => item.shop_id == item1.shop_id);
        if (find !== -1) {
            const goodsList = parmsCar.value.list[find].goods_list; //当前取消的数据
            const goodsIndex = goodsList.findIndex((it) => it.goods_sku_price_id == item1.goods_sku_price_id);
            if (goodsIndex != -1) {
                console.log('找到了取消的商品');
                parmsCar.value.list[find].goods_list.splice(parmsCar.value.list[find].goods_list[goodsIndex], 1);
                console.log(123123, parmsCar.value.list);
            }
        }
    }
};
// 底部全选
const allxuan = () => {
    allx.value = !allx.value;
    // 如果选中全选，就遍历其他商品按钮
    if (allx.value == true) {
        parmsCar.value.list = [];
        shops.value.forEach((item) => {
            // 添加数据
            parmsCar.value.list.push({
                shop_id: item.id,
                goods_list: []
            });
            parmsCar.value.list.forEach((it) => {
                if (it.shop_id == item.id) {
                    it.goods_list = item.goodsList.map((goods) => ({
                        goods_id: goods.goods_id,
                        goods_sku_price_id: goods.goods_sku_price_id,
                        goods_num: goods.goods_num
                    }));
                }
            });

            if (item.ischall != true) {
                item.ischall = true; //选中商铺按钮
                item.goodsList.forEach((it) => {
                    if (it.ischak != true) {
                        idss.value.push(it.id);
                        it.ischak = true; //选中所有商品按钮
                        totalPrice.value = Number(totalPrice.value) + Number(it.goods.price);
                    }
                });
            }
        });
    } else {
        shops.value.forEach((item) => {
            item.ischall = false; //取消商铺按钮
            item.goodsList.forEach((it) => {
                it.ischak = false; //取消所有商铺按钮
                totalPrice.value = 0; //取消全选把价格清空
            });
        });
        parmsCar.value.list = [];
        idss.value = [];
    }
    console.log(123123, parmsCar.value.list);
};
// 商品增加和减少计算出价格
const handleChange = (it) => {
    console.log(it);
    // 判断是增加还是减少计算出价格
    if (it.goods_num > it.topzhi) {
        console.log('增加', it.goods_num, it.topzhi);
        let newPrice = Number(it.snapshot_price) * Number(it.goods_num);
        it.goods.price = newPrice.toFixed(2); //每个商品的价格
        // 如果当前商品按钮选中再计算总价
        if (it.ischak == true) {
            totalPrice.value += Number(it.snapshot_price);
        }
        carUPdate(it.goods_id, it.goods_num, 'cover', it.sku_price.id); //更新购物车
    } else {
        console.log('减少', it.goods.price);
        let newPrice = Number(it.goods.price) - Number(it.snapshot_price);
        it.goods.price = newPrice.toFixed(2); //每个商品的价格
        // 如果当前商品按钮选中计算总价格
        if (it.ischak == true) {
            totalPrice.value -= Number(it.snapshot_price);
        }
        carUPdate(it.goods_id, it.goods_num, 'cover', it.sku_price.id); //更新购物车
    }
    it.topzhi = it.goods_num; //赋值商品数量
};
// 增加状态
const countPrice = () => {
    shops.value.forEach((item) => {
        item.ischall = false; //增加店铺选中框状态
        item.goodsList.forEach((it) => {
            it.ischak = false; //增加商品选中框状态
            it.topzhi = it.goods_num; //记录上一次的值
            // 如果有的商品不是1个的话计算他的价格
            let newPrice = Number(it.snapshot_price) * Number(it.goods_num);
            it.goods.price = newPrice.toFixed(2); //每个商品的价格
        });
    });
};
// 获取购物车列表
const getCarList = async () => {
    const ret = await carList();
    list11.value = ret.data;
};
// 循环购物车key
const shops = computed(() => Object.values(list11.value));
// 获取用户信息
const userInfo = async () => {
    const ret = await user();
    if (ret.code == 1) {
        parmsCar.value.voucher = ret.data.voucher;
        console.log('个人信息', parmsCar.value);
    } else {
        utils('数据加载失败！');
    }
};
//点击店铺跳转店铺详情
const shopDetas1 = (item) => {
    uni.navigateTo({
        url: `/pages/sub/details?ids=${item.id}`
    });
};
//点击店铺商品跳转商品详情
const shopDetas2 = (it) => {
    console.log(111, it);
    uni.navigateTo({
        url: `/pages/sub/shopDetails?ids=${it.goods_id}`
    });
};
</script>

<style lang="scss" scoped>
// 下拉框的样式
.gouwuce {
    display: flex;
    margin: 0 20rpx;
    .jie {
        margin: 0 20rpx;
    }
    .btnsty {
        padding: 20rpx;
        border-radius: 30rpx;
        color: #fff;
        background-color: #ff9a01;
    }
}
::v-deep .uni-stat__select {
    background-color: #f6f6f6;
    border: none !important;
    padding: 4rpx !important;
    width: 200rpx;
    border-radius: 10rpx !important;
    margin-top: 18rpx;
    margin-bottom: 30rpx;
}
::v-deep .uni-select {
    border: none !important;
    padding: 8rpx !important;
    height: 40rpx;
}
::v-deep .uni-select__input-text {
    color: #9e9e9e;
    font-size: 26rpx;
}
.content {
    // 底部
    .fotter {
        .fot-right {
            display: flex;
            align-items: center;
        }
        .fot-left {
            margin-left: 24rpx;
        }
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 120rpx;
        background-color: #fff;
        z-index: 9;
    }
    //
    .car-box {
        .box-bottom {
            // 底部价格
            .box-btm {
                .btm-right {
                    .carnum {
                        width: 134rpx;
                        height: 39rpx;
                    }
                }
                .btm-left {
                    color: #f8bb4f;
                }
                display: flex;
                align-items: center;
                justify-content: space-between;
            }
            .nickname {
                width: 360rpx;
                font-size: 26.02rpx;
                white-space: nowrap; /* 禁止换行 */
                overflow: hidden; /* 隐藏超出部分 */
                text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
            }
            .img {
                width: 152rpx;
                height: 120rpx;
                margin-right: 34rpx;
            }
            display: flex;
            align-items: center;
            margin-bottom: 56rpx;
            &:last-child {
                margin-bottom: 0;
            }
        }
        .box-top {
            display: flex;
            align-items: center;
            margin-bottom: 30rpx;
            .img {
                width: 28rpx;
                height: 26rpx;
                margin-left: 15rpx;
                margin-right: 10rpx;
            }
        }
        &:first-child {
            z-index: 1;
        }
        position: relative;
        padding: 32rpx 32rpx 30rpx 24rpx;
        background-color: #fff;
        border-radius: 20rpx;
        margin-bottom: 18rpx;
    }
    .positioning {
        height: 282rpx;
        background: linear-gradient(to bottom, #ffe8be, #f7f7f7);
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
    }
    background-color: #f7f7f7;
    min-height: 100vh;
    padding: 46rpx 30rpx 300rpx 30rpx;
}
</style>
